const Router = require('koa-router');
const common = require('../libs/common');
const response = require('../libs/result');
let router = new Router();

/**
 * @api {post} /api/v1/notice/check  检测是否有新通知
 * @apiDescription 检测是否有新通知
 * @apiName check
 * @apiParam (参数) {String} userid   用户id
 * @apiSampleRequest /api/v1/notice/check
 * @apiGroup notice
 * @apiVersion 1.0.0
 */
router.post('/check', async ctx => {
  try {
    let input = ctx.request.body;
    let auth_user = await ctx.db.query(`select * from auth_user where  id=? `, [parseInt(input.userid)]);
    if (auth_user.length == 0) {
      response(ctx, 201, '', 'no user')
      return;
    }
    auth_user = JSON.stringify(auth_user)
    auth_user = JSON.parse(auth_user)
    response(ctx, 200, auth_user[0].is_notice, '')
  } catch (error) {
    console.log(error);
    response(ctx, 201, '', 'error')
  }
})


/**
 * @api {post} /api/v1/notice/getnoticelist  通知列表
 * @apiDescription 通知列表
 * @apiName getnoticelist
 * @apiParam (参数) {String} user_id   用户id
 * @apiParam (参数) {String} channel   包名(com.vn.cashhoa.voi)
 * @apiParam (参数) {Number} page   page
 * @apiParam (参数) {Number} pageSize   pageSize
 * @apiSampleRequest /api/v1/notice/getnoticelist
 * @apiGroup notice
 * @apiVersion 1.0.0
 */
router.post('/getnoticelist', async ctx => {
  try {
    let input = ctx.request.body;
    let auth_user = await ctx.db.query(`select * from auth_user where  id=?`, [input.user_id]);
    auth_user = JSON.stringify(auth_user)
    auth_user = JSON.parse(auth_user)
    let page = parseInt(input.page);
    let pageSize = parseInt(input.pageSize);
    let content_push_message = await ctx.db.query(`select id,title,created_time,content,status,click_action,link from content_push_message where mobile=?  and channel=? order by last_push_time desc limit ?,?`, [auth_user[0].phone_number, input.channel, (page - 1) * pageSize, pageSize]);
    response(ctx, 200, content_push_message, '');
  } catch (error) {
    console.log(error);
    response(ctx, 201, '', 'error');
  }
})




/**
 * @api {post} /api/v1/notice/setread  设置已读
 * @apiDescription 设置已读
 * @apiName setread
 * @apiParam (参数) {String} noticeid   通知id
 * @apiParam (参数) {String} user_id   用户id
 * @apiSampleRequest /api/v1/notice/setread
 * @apiGroup notice
 * @apiVersion 1.0.0
 */
router.post('/setread', async ctx => {
  let { user_id, noticeid, channel } = ctx.request.body;
  let auth_user = await ctx.db.query(`select * from auth_user where  id=?`, [user_id]);
  auth_user = JSON.stringify(auth_user)
  auth_user = JSON.parse(auth_user)

  let content_push_message = await ctx.db.query(`update content_push_message set status=1 where mobile=?  and channel=? and id=?`, [auth_user.phone_number, channel, noticeid]);
  response(ctx, 200, content_push_message, '');
})

module.exports = router.routes()